package net.lanelife.casino.cms.web.controller;

import javax.servlet.ServletRequest;

import net.lanelife.casino.caipiao.dto.admin.UserCreateDTO;
import net.lanelife.casino.caipiao.dto.admin.UserDTO;
import net.lanelife.casino.caipiao.dto.admin.UserLayerDTO;
import net.lanelife.casino.caipiao.dto.admin.UserTable;
import net.lanelife.casino.caipiao.dto.admin.UserUpdateDTO;
import net.lanelife.casino.caipiao.entity.User;
import net.lanelife.casino.caipiao.service.api.IUserLayerService;
import net.lanelife.casino.caipiao.service.api.IUserService;
import net.lanelife.casino.cms.web.controller.support.CRUDController;
import net.lanelife.casino.common.service.support.IGenericService;
import net.lanelife.casino.common.utils.PasswordUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = UserController.PATH)
public class UserController extends CRUDController<User, Integer, UserDTO, UserCreateDTO, UserUpdateDTO, UserTable<UserDTO>> {
	
	public static final String PATH = "/user";
	
	public UserController() {
		super(PATH);
	}

	@Autowired
	private IUserService userService;
	
	@Autowired
	private IUserLayerService userLayerService;
	
	@Override
	protected IGenericService<User, Integer> getService() {
		return userService;
	}
	
	@Override
	protected void preList(Model model, ServletRequest request) throws Exception {
		model.addAttribute("userLayerList", userLayerService.findAll(UserLayerDTO.class));
	}

	@Override
	protected void preCreate(Model model, UserCreateDTO createDTO) throws Exception {
		model.addAttribute("userLayerList", userLayerService.findAll(UserLayerDTO.class));
	}
	
	@Override
	protected void postCreate(Model model, UserCreateDTO createDTO, BindingResult br) throws Exception {
		String salt = PasswordUtils.generateSalt();
		createDTO.setPasswordSalt(salt);
		createDTO.setLoginPassword(PasswordUtils.encode(createDTO.getLoginPassword(), salt));
	}
	
	@Override
	protected void preUpdate(Model model, UserUpdateDTO updateDTO) throws Exception {
		model.addAttribute("userLayerList", userLayerService.findAll(UserLayerDTO.class));
	}

}
